package com.example.pacs.dicom.listener;

import com.example.pacs.dicom.event.NewFileEvent;
import com.example.pacs.dicom.server.cstoresup.DicomReader;
import com.example.pacs.service.PatientService;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.UID;
import org.dcm4che3.io.DicomInputStream;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 新建文件事件监听器
 */
@Slf4j
// 这里一定要将监听器注入IOC容器中
@Component
public class NewFileEventListener {

    @Resource
    private EventBus eventBus;

    @Resource
    private PatientService patientService;

    /**
     * 在类调用之前执行该方法,将自己注册到事件总线中
     */
    @PostConstruct
    public void register() {
        eventBus.register(this);
    }

    /**
     * 在类销毁之前调用该方法,将该类从事件总线中移除
     */
    @PreDestroy
    public void unregister() {
        eventBus.unregister(this);
    }

    /**
     * Subscribe:guava组件定义一个侦听器的方法
     * 这里对新建文件这个事件进行监听和处理
     */
    @Subscribe
    public void dealNewFileEvent(NewFileEvent fileEvent) {
        try (DicomInputStream dicomInputStream = new DicomInputStream(fileEvent.getFile())) {
            // 构建DICOM输入流
            // 设置输入流形式为URI
            dicomInputStream.setIncludeBulkData(DicomInputStream.IncludeBulkData.URI);
            // 读取传输的date set,也就是传输的具体数据
            Attributes attributes = dicomInputStream.readDataset(-1, -1);
            // 获取meta info,如果为空的话则使用默认编码方式进行创建
            Attributes fmi = dicomInputStream.readFileMetaInformation() == null ? dicomInputStream.readFileMetaInformation() : attributes.createFileMetaInformation(UID.ImplicitVRLittleEndian);
            // 构建DicomReader
            DicomReader dicomReader = new DicomReader(attributes, fmi);
            // dcm信息入库
            patientService.insertAllPatientInfo(dicomReader);
        } catch (Exception e) {
            log.error("deal newFileEvent error! message is :" + e.getMessage(), e);
        }
    }
}
